import useUserStore from "@/store/modules/useUserStore";
import useBiliStore from "@/store/modules/useBiliStore";

const BILI_AUTH_URL = "https://passport.bilibili.com";
const BILI_LIVE_URL = "https://api.live.bilibili.com";
const BILI_URL = "https://api.bilibili.com";
const BILI_OPEN_URL = "https://live-open.biliapi.com";
//获取登录二维码
function getQRCode() {
  return window.electronAPI.axios({
    method: "GET",
    url: `${BILI_AUTH_URL}/x/passport-login/web/qrcode/generate`,
    params: {
      source: "main-mini"
    }
  });
}

//检查登录态
function getLoginStatus(code) {
  if (!code) return Promise.reject("参数校检失败");
  return window.electronAPI.axios({
    method: "GET",
    url: `${BILI_AUTH_URL}/x/passport-login/web/qrcode/poll`,
    params: {
      qrcode_key: code,
      source: "main-fe-header"
    }
  });
}

//发送弹幕消息
async function sendDanmuMsg(roomId = "", msg = "") {
  const userStore = useUserStore();
  if (!userStore.hasLogin) return Promise.reject("账号未登录");
  if (!roomId || !msg) return Promise.reject("参数校检失败");
  const cookies = await window.electronAPI.getCookie({
    domain: "bilibili.com"
  });
  const jct = cookies.find(v => v.name == "bili_jct")?.value ?? "";
  return window.electronAPI
    .axios({
      method: "POST",
      url: `${BILI_LIVE_URL}/msg/send`,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      withCredentials: true,
      data: {
        bubble: 0,
        color: "16777215",
        mode: 1,
        fontsize: 25,
        rnd: Date.now() / 1e3,
        roomid: roomId,
        csrf: jct,
        csrf_token: jct,
        msg
      },
      loading: true,
      auth: true
    })
    .then(data => {
      //window.$message.success("发送成功");
      console.log("sendDanmuMsg:", data);
      return data;
    });
}

//获取B站用户信息
function getUserInfo() {
  return window.electronAPI.axios({
    method: "GET",
    url: `${BILI_LIVE_URL}/xlive/web-ucenter/user/get_user_info`,
    withCredentials: true,
    auth: true
  });
}

//获取关注数,粉丝数
function getRelationStat(uid) {
  if (!uid) return Promise.reject("参数校检失败");
  return window.electronAPI.axios({
    method: "GET",
    url: `${BILI_URL}/x/relation/stat`,
    params: {
      vmid: `${uid}`,
      jsonp: "jsonp"
    }
  });
}

//获取获赞数,阅读数
function getSpaceUpstat(uid) {
  if (!uid) return Promise.reject("参数校检失败");
  return window.electronAPI.axios({
    method: "GET",
    url: `${BILI_URL}/x/space/upstat`,
    params: {
      mid: uid,
      jsonp: "jsonp"
    },
    withCredentials: true
  });
}

//获取直播间信息
function getRoomInfo() {
  return window.electronAPI.axios({
    method: "GET",
    url: `${BILI_LIVE_URL}/xlive/app-blink/v1/room/GetInfo`,
    params: {
      platform: "pc"
    },
    withCredentials: true
  });
}

//获取用户基本信息
function getBaseUserInfo() {
  const userStore = useUserStore();
  const biliStore = useBiliStore();
  return getUserInfo()
    .then(data => {
      return Promise.all([
        getRelationStat(data.uid),
        getSpaceUpstat(data.uid),
        getRoomInfo()
      ]).then(values => {
        return Promise.resolve(
          Object.assign(data, {
            follower: values[0].follower ?? 0,
            following: values[0].following ?? 0,
            likes: values[1].likes ?? 0,
            article_view: values[1].article?.view ?? 0,
            archive_view: values[1].archive?.view ?? 0,
            room_id: values[2].room_id,
            medal_name: values[2].medal_name,
            medal_status: values[2].medal_status
          })
        );
      });
    })
    .then(data => {
      userStore.setUser(data);
      //if (data.room_id) biliStore.roomId = data.room_id;
      return data;
    });
}
//项目开启
function startBiliApp() {
  const biliStore = useBiliStore();
  if (!biliStore.code) return Promise.reject("参数错误");
  return window.electronAPI
    .axios({
      method: "POST",
      url: `${BILI_OPEN_URL}/v2/app/start`,
      data: {
        code: biliStore.code,
        app_id: 1682844010492
      },
      biliAuth: true
    })
    .then(data => {
      biliStore.roomId = data.anchor_info?.room_id;
      biliStore.gameId = data.game_info?.game_id;
      biliStore.wsInfo = data.websocket_info;
      return data;
    });
}
//项目关闭
function endBiliApp() {
  const biliStore = useBiliStore();
  if (!biliStore.gameId) return Promise.reject("参数错误");
  return window.electronAPI.axios({
    method: "POST",
    url: `${BILI_OPEN_URL}/v2/app/end`,
    data: {
      game_id: biliStore.gameId,
      app_id: 1682844010492
    },
    biliAuth: true
  });
}
//项目心跳
let timeId: any = -1;
function heartBiliApp() {
  const biliStore = useBiliStore();
  return window.electronAPI
    .axios({
      method: "POST",
      url: `${BILI_OPEN_URL}/v2/app/heartbeat`,
      data: {
        game_id: biliStore.gameId
      },
      biliAuth: true
    })
    .then(data => {
      console.log("heart:", data);
      if (timeId) clearTimeout(timeId);
      timeId = setTimeout(() => {
        heartBiliApp();
      }, 50 * 1000);
    });
}
export {
  getQRCode,
  getLoginStatus,
  sendDanmuMsg,
  getBaseUserInfo,
  startBiliApp,
  endBiliApp,
  heartBiliApp
};
